﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HustQQInterface;
using System.Threading;
using HustQQModel;

namespace HustQQClient.MsgDispatcher
{
    public class NetImplement:INetInterface
    {

        public OESClient Client = new OESClient();

        static EventWaitHandle waitEvt = new System.Threading.EventWaitHandle(false, EventResetMode.ManualReset);

        static List<object> waitObjs = new List<object>();
        public NetImplement()
        {
            Client = new OESClient();
            Client.ReceivedTxt += new EventHandler(Client_ReceivedTxt);
            Client.InitializeClient();
        }

        void Client_ReceivedTxt(object sender, EventArgs e)
        {
            waitObjs.Clear();
            string[] msgs = sender.ToString().Split('$');
            switch (msgs[0])
            {
                case "Reply":
                    {
                        switch (msgs[1])
                        {

                            #region 登录注册退出
                            case "Register":
                                {
                                    waitObjs.Add(msgs[2]);
                                    waitEvt.Set();
                                }
                                break;
                            case "Login":
                                {
                                    if (msgs[2] == "Success")
                                    {
                                        waitObjs.Add(true);
                                    }
                                    else if (msgs[2] == "Fail")
                                    {
                                        waitObjs.Add(false);
                                        waitObjs.Add(msgs[3]);
                                    }
                                    waitEvt.Set();
                                }
                                break;
                            case "Logout":
                                {
                                    if (msgs[2] == "Success")
                                    {
                                        waitObjs.Add(true);
                                    }
                                    else if (msgs[2] == "Fail")
                                    {
                                        waitObjs.Add(false);
                                        waitObjs.Add(msgs[3]);
                                    }
                                    waitEvt.Set();
                                }
                                break;
                            #endregion 登录注册

                            case "ChangeState":
                                {

                                }
                                break;
                            #region 初始界面
                            case "GetFriendList":
                                {
                                    List<User> friendList = new List<User>();
                                    int p=2;
                                    while (p < msgs.Length)
                                    {
                                        User u = new User();
                                        u.qq_ID = msgs[p++];
                                        u.face = Int32.Parse(msgs[p++]);
                                        u.name = msgs[p++];
                                        p++;
                                        u.note = msgs[p++];
                                        u.group = msgs[p++];
                                        if (msgs[p] == "T")
                                        {
                                            u.online = true;
                                        }
                                        else if (msgs[p] == "F")
                                        {
                                            u.online = false;
                                        }
                                        p++;
                                        friendList.Add(u);
                                    }
                                    waitObjs.Add(friendList);
                                    waitEvt.Set();
                                }
                                break;
                            case "GetTeam":
                                {
                                    List<Team> teamList = new List<Team>();
                                    int p = 2;
                                    while (p < msgs.Length)
                                    {
                                        Team t = new Team();
                                        t.teamID = msgs[p++];
                                        t.teamName = msgs[p++];
                                        t.ower = msgs[p++];
                                        teamList.Add(t);
                                    }
                                    waitObjs.Add(teamList);
                                    waitEvt.Set();
                                }
                                break;
                            case "GetTeamMember":
                                {
                                    List<User> memberList = new List<User>();
                                    int p = 2;
                                    while (p < msgs.Length)
                                    {
                                        User u = new User();
                                        u.qq_ID = msgs[p++];
                                        u.face = Int32.Parse(msgs[p++]);
                                        u.name = msgs[p++];
                                       
                                        u.note = msgs[p++];
                                        if (msgs[p] == "T")
                                        {
                                            u.online = true;
                                        }
                                        else if (msgs[p] == "F")
                                        {
                                            u.online = false;
                                        }
                                        p++;
                                        memberList.Add(u);
                                    }
                                    waitObjs.Add(memberList);
                                    waitEvt.Set();
                                }
                                break;
                            #endregion
                            #region 信息查询
                            case "FindMyself":
                                {
                                    User me = new User();
                                    me.qq_ID = msgs[2];
                                    me.face = Int32.Parse(msgs[3]);
                                    me.name = msgs[4];
                                    me.note = msgs[5];
                                    waitObjs.Add(me);
                                    waitEvt.Set();               
                                }
                                break;
                            case "FindFriend":
                                {
                                    User friend = new User();
                                    friend.qq_ID = msgs[2];
                                    friend.face = Int32.Parse(msgs[3]);
                                    friend.name = msgs[4];
                                    friend.note = msgs[5];
                                    if ((string)msgs[6] == "T")
                                    {
                                        friend.online = true;
                                    }
                                    else
                                    {
                                        friend.online = false;
                                    }
                                    waitObjs.Add(friend);
                                    waitEvt.Set();        
                                }
                                break;
                            case "FindTeam":
                                {
                                    Team team = new Team();
                                    team.teamID = msgs[2];
                                    team.teamName = msgs[3];
                                    waitObjs.Add(team);
                                    waitEvt.Set();   
                                }
                                break;
                            #endregion

                            case "AddFriend":
                                {
                                    string Q2 = msgs[2];
                                    string result = msgs[3];
                                    string message = msgs[4];
                                    string group = msgs[5];
                                    string note = msgs[6];
                                    if (result == "T")
                                    {
                                        AddFriendReply(Q2, true, message, group);
                                    }
                                    else if (result == "F")
                                    {
                                        AddFriendReply(Q2, false, message, group);
                                    }
                                }
                                break;
                            case "CreateTeam":
                                {
                                    String  teamName= msgs[2];
                                    String teamId = msgs[3];
                                    waitObjs.Add(teamName);
                                    waitObjs.Add(teamId);
                                    waitEvt.Set();   
                                }
                                break;

                            case "AddTeam":
                                {
                                    string T = msgs[2];
                                    string result = msgs[3];
                                    string message = msgs[4];
                                    if (result == "T")
                                    {
                                        AddTeamReply(T, true, message);
                                    }
                                    else if (result == "F")
                                    {
                                        AddTeamReply(T, false, message);
                                    }
                                }
                                break;

                            #region 文件传输消息
                            case "SendFile":
                                {
                                    if(ConfirmSendFile!=null)
                                        ConfirmSendFile(msgs[4] == "OK" ? true : false);
                                    if (msgs[4] == "OK")
                                    {
                                        Client.Port.FilePath = fileInfo.FilePath;
                                        Client.Port.FileSendEnd+=new EventHandler(Port_FileSendEnd);
                                        Client.SendFile();
                                    }
                                }
                                break;
                            #endregion 文件传输消息
                        }
                    }
                    break;
                case "Command":
                    {
                        switch (msgs[1])
                        {
                            case "AcceptFriend":
                                {
                                    String Q1 = msgs[2];
                                    String Q2 = msgs[3];
                                    String message = msgs[4];
                                    String group1 = msgs[5];
                                    String note1 = msgs[6];
                                    AddFriendResult result = AddFriendRequest(Q1, message);
                                    String reply = "Reply" + "$"
                                        + "AcceptFriend" + "$"
                                        + Q1 + "$"
                                        + Q2 + "$";
                                    if (result.accept)
                                    {
                                        //未处理备注
                                        reply += "T" + "$"
                                            + message + "$"
                                            + group1 + "$"
                                            + note1 + "$"
                                            + result.group + "$"
                                            + result.note;
                                    }
                                    else
                                    {
                                        reply += "F" + "$"
                                            + message + "$"
                                            + "" + "$"
                                            + "" + "$"
                                            + "" + "$"
                                            + "";
                                    }
                                    Client.SendTxt(reply);
                                }
                                break;
                            case "AcceptTeamMember":
                                {
                                    string Q = msgs[2];
                                    string T = msgs[3];
                                    string message = msgs[4];
                                    AddTeamResult result =  AddTeamRequest(Q, T, message);
                                    String reply = "Reply" + "$"
                                      + "AcceptTeamMember" + "$"
                                      + Q + "$"
                                      + T + "$";
                                    if (result.accept)
                                    {
                                        //未处理备注
                                        reply += "T" + "$"
                                            + message;
                                    }
                                    else
                                    {
                                        reply += "F" + "$"
                                            + message;
                                    }
                                    Client.SendTxt(reply);
                                }
                                break;
                            
                            #region 单聊
                            case "ReceiveMessage":
                                {
                                    RecieveTextFromSingle(msgs[2], msgs[3], DateTime.Parse(msgs[4]));
                                }
                                break;
                            #endregion 单聊

                            #region 群聊
                            case "ReceiveTeamMessage":
                                {
                                    RecieveTextFromTeam(msgs[3], msgs[2], msgs[4], DateTime.Parse(msgs[5]));
                                }
                                break;
                            #endregion 群聊

                            #region 文件传输消息
                            case "SendFile":
                                {
                                    fileInfo=new FileInformation(msgs[4], long.Parse(msgs[5]),Guid.Parse(msgs[6]),msgs[2],msgs[3]);
                                    ConfirmRecieveFile(msgs[2],fileInfo , DateTime.Now);
                                    
                                }
                                break;
                            case "SendOver":
                                {
                                    ReceiveFile(fileInfo.FilePath);
                                }
                                break;
                            case "ReceiveOver":
                                {
                                    if (ReceiveFileOver != null)
                                    {
                                        ReceiveFileOver(msgs[3], fileInfo, DateTime.Now);
                                    }
                                }
                                break;
                            #endregion 文件传输消息

                        }
                    }
                    break;
            }
        }
        #region INetInterface 成员

        #region 单聊
        public void SendTextToSingle(string myId, string friendId, string text)
        {
            Client.SendTxt("Command$SendMessage$"+DateTime.Now.ToString()+"$"+myId.ToString()+"$"+friendId.ToString()+"$"+text);
        }
        #endregion 单聊

        #region 群聊
        public void SendTextToTeam(string myId, string teamId, string text)
        {
            Client.SendTxt("Command$SendTeamMessage$"+DateTime.Now.ToString()+"$"+myId.ToString()+"$"+teamId.ToString()+"$"+text);
        }
        #endregion 群聊

        public event SingleTextMsg RecieveTextFromSingle;

        public event TeamTextMsg RecieveTextFromTeam;

        public void SendPictureToSingle(string myId, string friendId, string picPath)
        {
            throw new NotImplementedException();
        }

        public void SendPictureToTeam(string myId, string teamId, string picPath)
        {
            throw new NotImplementedException();
        }

        public event SinglePicMsg RecievePicFromSingle;

        public event TeamPicMsg RecievePicFromTeam;

        public event AddFriendMsg AddFriendRequest;
        public event AddFriendReply AddFriendReply;

        public event AddTeamMsg AddTeamRequest;
        public event AddTeamReply AddTeamReply;
        #region 文件传输部分
        public event FileMsg ConfirmRecieveFile;

        public event BooleanMsg ConfirmSendFile;

        public event Action SendFileOver;

        public event FileMsg ReceiveFileOver;

        public FileInformation fileInfo ;

        public void SendFile(string myId, string friendId, string filePath)
        {
            FileInformation fi=new FileInformation(filePath);
            fileInfo=fi;
            fileInfo.SendQQ = myId;
            fileInfo.ReceiveQQ = friendId;
            Client.SendTxt("Command$SendFile$" + myId.ToString() + "$" + friendId.ToString() + "$" + fi.FileName + "$" + fi.FileSize + "$" + fi.FileId.ToString());
        }
        //Client.Port.FileSendEnd += new EventHandler(Port_FileSendEnd);
        //    Client.Port.FilePath = filePath;
        //    Client.SendFile();
        public void ReceiveFile(string filePath)
        {
            Client.Port.FileReceiveEnd += new EventHandler(Port_FileReceiveEnd);
            Client.Port.FilePath = filePath;
            Client.ReceiveFile();
        }

        void Port_FileReceiveEnd(object sender, EventArgs e)
        {
            Console.WriteLine("Recieve Over");
            Client.SendTxt("Command$ReceiveOver$" + fileInfo.SendQQ + "$" + fileInfo.ReceiveQQ + "$" + fileInfo.FileId);
        }

        void Port_FileSendEnd(object sender, EventArgs e)
        {
            Console.WriteLine("Send Over");
            Client.SendTxt("Command$SendOver$"+fileInfo.SendQQ+"$"+fileInfo.ReceiveQQ+"$" + fileInfo.FileId);
            if (SendFileOver != null)
            {
                SendFileOver();
            }
        }

        public void ReplyConfirm(bool isRev)
        {
            Client.SendTxt("Reply$SendFile$" + fileInfo.SendQQ + "$" + fileInfo.ReceiveQQ + "$" + (isRev ? "OK" : "NO") + "$" + fileInfo.FileId.ToString());
        }

        #endregion 文件传输部分

        #region 登录注册退出
        public bool Login(string userId, string pwd)
        {
            Client.SendTxt("Command$Login$" + userId.ToString() + "$" + pwd.ToString() + "$State");
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                if ((Convert.ToBoolean(waitObjs[0])))
                {
                    return true;
                }
                else
                {
                    Console.WriteLine(waitObjs[1].ToString());
                    return false;
                }
            }
            return true;
        }

        public string Register(HustQQModel.User u)
        {
            Client.SendTxt("Command$Register$" + u.name + "$" + u.password+"$"+u.face.ToString()+"$"+u.age.ToString()+"$"+u.sex.ToString()+"$"+u.birthday+"$"+u.telephone+"$"+u.address);
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                return waitObjs[0].ToString();
            }
            return "-1";
        }

        public bool Logout(string userId)
        {
            Client.SendTxt("Command$Logout$" + userId.ToString());
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                if ((Convert.ToBoolean(waitObjs[0])))
                {
                    return true;
                }
                else
                {
                    Console.WriteLine(waitObjs[1].ToString());
                    return false;
                }
            }
            return true;
        }
        #endregion 登录注册
        #region 获得好友群群友信息
        public List<User> GetFriend(string userId)
        {
            Client.SendTxt("Command$GetFriendList$" + userId.ToString());
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                List<User>friends = new List<User>();
                friends= (List<User>)waitObjs[0];
                return friends;
            }
            return null;
        }
        public List<Team> GetGroup(string userId)
        {
            Client.SendTxt("Command$GetTeam$" + userId.ToString());
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                List<Team>teams = new List<Team>();
                teams = (List<Team>)waitObjs[0];
                return teams;
            }
            return null;
        }
        public List<User> GetTeamMember(string userId, string teamId)
        {
            Client.SendTxt("Command$GetTeamMember$" + userId.ToString() + "$" + teamId.ToString());
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                List<User> teamMembers = new List<User>();
                teamMembers = (List<User>)waitObjs[0];
                return teamMembers;
            }
            return null;
        }
        #endregion
        #region 查找好友群信息
        public HustQQModel.User GetMyself(string userId)
        {
            Client.SendTxt("Command$FindMyself$" + userId.ToString());
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                User u = (User)waitObjs[0];
                return u;
            }
            return null;
        }
        public User FindFriend(string userId, string findUerId)
        {
            Client.SendTxt("Command$FindFriend$" + userId.ToString()+"$"+findUerId);
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                User u = (User)waitObjs[0];
                return u;
            }
            return null;
        }
        public Team FindTeam(string userId, string teamId)
        {
            Client.SendTxt("Command$FindTeam$" + userId.ToString() + "$" + teamId);
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                Team t = (Team)waitObjs[0];
                return t;
            }
            return null;
        }
        #endregion

        public void AddFriendToUser(string myId, string friendId,string message, string groupName)
        {
            Client.SendTxt("Command$AddFriend$" + myId + "$" + friendId + "$" + message +"$"+groupName + "$");
        }
        public string CreatTeam(string myId, string teamName)
        {
            Client.SendTxt("Command$CreateTeam$" + myId + "$" + teamName);
            if (waitEvt.WaitOne())
            {
                waitEvt.Reset();
                return waitObjs[1].ToString();
            }
            return "-1";
        }
        public void AddFriendToTeam(string userId, string teamId, string message)
        {
            Client.SendTxt("Command$AddTeam$" + userId + "$" + teamId + "$" + message);
        }
        #region 未实现
        public bool DelFriendFromUser(string myId, string friendId)
        {
            throw new NotImplementedException();
        }

        public bool DelFriendFromGroup(string myId, string friendId, string groupName)
        {
            throw new NotImplementedException();
        }

        public bool SetUserInformation(HustQQModel.User u)
        {
            throw new NotImplementedException();
        }

        public bool SetTeamInformation(HustQQModel.Team t)
        {
            throw new NotImplementedException();
        }

        public bool DelFriendFromTeam(string teamId, string userId)
        {
            throw new NotImplementedException();
        }

        public bool SetIpPort(string userId, HustQQModel.IpPort ipPort)
        {
            throw new NotImplementedException();
        }

        public HustQQModel.IpPort GetIpPort(string userId)
        {
            throw new NotImplementedException();
        }
        #endregion
        #endregion

        #region INetInterface 成员


        public User GetUserInformation(string userId, bool isDetail)
        {
            throw new NotImplementedException();
        }

        public bool AddFriendToUser(string myId, string friendId, string groupName)
        {
            throw new NotImplementedException();
        }

        public bool AddFriendToGroup(string myId, string friendId, string groupName)
        {
            throw new NotImplementedException();
        }

        public Team GetTeamInformation(string teamId, bool isDetail)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region INetInterface 成员


        public string NewTeamToUser(string myId)
        {
            throw new NotImplementedException();
        }

        public bool AddFriendToTeam(string teamId, string userId)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
